//
//  KGeneralCommentsController.m
//  Keping
//
//  Created by a on 2017/9/15.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KGeneralCommentsController.h"
#import "KBbsTopicsDetailRequest.h"

@interface KGeneralCommentsController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UILabel *nikeLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UIView *commentView;
@property (nonatomic, strong) UITableView *tableView;
/**底部评论框*/
@property (nonatomic, strong)UITextField*commentField;
@property (nonatomic, strong) NSMutableArray<KBbsPostsViews *> *bbsPostsViews;
@property (nonatomic, copy) NSString *selectID;

@end

@implementation KGeneralCommentsController

- (NSMutableArray<KBbsPostsViews *> *)bbsPostsViews {
    if (!_bbsPostsViews) {
        _bbsPostsViews = [[NSMutableArray alloc] init];
    }
    return _bbsPostsViews;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
}
-(void)setUI
{
    self.navigationItem.title=@"Comments";
    self.view.backgroundColor=[UIColor whiteColor];
    //头像
    self.iconView =[[UIImageView alloc]init];
    [self.view addSubview:self.iconView];
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(15);
        make.left.equalTo(self.view).offset(15);
        make.width.height.mas_equalTo(40);
    }];
    
    //昵称
    self.nikeLabel=[[UILabel alloc]init];
    self.nikeLabel.font = HJFont(K_FactorW(17));
    self.nikeLabel.textColor = [UIColor colorWithHexString:@"#959595"];
    [self.view addSubview:self.nikeLabel];
    [self.nikeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.iconView.mas_top);
        make.left.equalTo(self.iconView.mas_right).offset(15);
        make.height.mas_equalTo(17);
        make.width.mas_equalTo(kScreenWidth - CGRectGetMaxX(self.iconView.frame) - 15 - 20);
    }];
    
    //时间
    self.timeLabel=[[UILabel alloc]init];
    self.timeLabel.font = HJFont(K_FactorW(14));
    self.timeLabel.textColor=[UIColor colorWithHexString:@"#d6d6d6"];
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.nikeLabel.mas_bottom);
        make.height.mas_equalTo(13);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    //内容
    self.contentLabel=[[UILabel alloc]init];
    [self.view addSubview:self.contentLabel];
    self.contentLabel.textColor=[UIColor colorWithHexString:@"101010"];
    self.contentLabel.font = HJFont(K_FactorW(17));
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nikeLabel.mas_bottom).offset(10);
        make.left.equalTo(self.nikeLabel.mas_left);
        make.right.equalTo(self.timeLabel.mas_right);
        make.height.mas_equalTo(self.bbsPostView.contentHeight);
    }];
    
    UIView *commentBg = [[UIView alloc] init];
    commentBg.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    [self.view addSubview:commentBg];
    [commentBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(60);
    }];
    
    
    //地图评论输入框
    self.commentField=[[UITextField alloc]init];
    [commentBg addSubview:self.commentField];
    self.commentField.placeholder=@"write a comment";
    self.commentField.delegate = self;
    self.commentField.layer.masksToBounds=YES;
    self.commentField.layer.borderColor=[UIColor colorWithHexString:@"#c1c1c1"].CGColor;
    self.commentField.layer.borderWidth=1;
    self.commentField.layer.cornerRadius = 22.5;
    self.commentField.returnKeyType = UIReturnKeySend;
    self.commentField.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, 40)];
    self.commentField.leftViewMode=UITextFieldViewModeAlways;
    [self.commentField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(commentBg.mas_centerY);
        make.left.equalTo(commentBg.mas_left).offset(15);
        make.right.equalTo(commentBg.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    
    //评论区
    self.commentView=[[UIView alloc]init];
    [self.view addSubview:self.commentView];
    [self.commentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(20);
        make.left.equalTo(self.contentLabel.mas_left);
        make.right.equalTo(self.contentLabel.mas_right);
        make.bottom.equalTo(self.commentField.mas_top).offset(-20);
    }];
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor=[UIColor colorWithHexString:@"#f2f2f2"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.commentView addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.left.equalTo(self.commentView);
    }];
    
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingString:self.bbsPostView.profile]] placeholderImage:[UIImage imageNamed:KImagePlaceholder]];
    self.nikeLabel.text = self.bbsPostView.realName;
    self.timeLabel.text = self.bbsPostView.timeTitle;
    self.contentLabel.text = self.bbsPostView.content;
}

- (void)setBbsPostView:(KBbsPostsViews *)bbsPostView {
    if (!bbsPostView) {
        return;
    }
    _bbsPostView = bbsPostView;
}

- (void)getData {
    [super getData];
    [self showLoading];
    WEAKSELF
    __block kBbsGeneralCommentsDetailRequest *detail = [[kBbsGeneralCommentsDetailRequest alloc] initWithBbspostId:self.bbsPostID];
    __block KBbsGeneralCommentsRequest *comment = [[KBbsGeneralCommentsRequest alloc] init];
    comment.params = @{@"postsId":self.bbsPostID};
    KBatchRequest *request = [[KBatchRequest alloc] initWithRequestArray:@[detail, comment]];
    [request startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf hideHUD];
        
        NSDictionary *detailDict = detail.responseObject;
        NSInteger detailStatus = [[detailDict objectForKey:@"statusCode"] integerValue];
        if (detailStatus == 200) {
            KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:[detailDict objectForKey:@"bbsPostsView"]];
            weakSelf.bbsPostView = bbs;
            [weakSelf setUI];
        } else {
            [weakSelf showErrorText:[detailDict objectForKey:@"msg"] errCode:detailStatus];
            return;
        }
        
        
        NSDictionary *dict = comment.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            [weakSelf.bbsPostsViews removeAllObjects];
            NSArray *arr = [dict objectForKey:@"bbsPostsViews"];
            for (NSDictionary *tmp in arr) {
                KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:tmp];
                [weakSelf.bbsPostsViews addObject:bbs];
            }
            [weakSelf.tableView reloadData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(KBatchRequest * _Nonnull batchRequest) {
        KLog(@"detailDict :%@",detail);
        [weakSelf hideHUD];
        [weakSelf showError:batchRequest.failedRequest.error];
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    kBbsGeneralAndPost *andPost =  [[kBbsGeneralAndPost alloc] init];
    if (self.selectID) {
        andPost.params = @{@"content":textField.text,@"curriculumDifficulty":self.selectID,@"useExperience":@"notice"};
    } else {
        andPost.params = @{@"content":textField.text,@"teachingLength":self.bbsPostView.id,@"useExperience":@"notice"};
    }
    
    WEAKSELF
    [andPost startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        [weakSelf hideHUD];
        if (status == 200) {
            weakSelf.selectID = nil;
            weakSelf.commentField.text = nil;
            [weakSelf showSuccess:[dict objectForKey:@"msg"]];
            [weakSelf getData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bbsPostsViews.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    cell.textLabel.numberOfLines = 0;
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:indexPath.row];
    if (!StringNotNull(bbs.toRealName)) {
        NSString *content = [NSString stringWithFormat:@"%@: %@",bbs.realName,bbs.content];
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:content];
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, bbs.realName.length + 1)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, bbs.realName.length + 1)];
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(bbs.realName.length + 2, bbs.content.length)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"101010"] range:NSMakeRange(bbs.realName.length + 2, bbs.content.length)];
        cell.textLabel.attributedText = att;
    } else {
        NSString *reply = @"Reply";
        NSString *content = [NSString stringWithFormat:@"%@ %@ %@: %@",bbs.realName,reply,bbs.toRealName,bbs.content];
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:content];
        //回复的人
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, bbs.realName.length + 1)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, bbs.realName.length + 1)];
        // Reply
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(reply.length + 1, reply.length + 1)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"101010"] range:NSMakeRange(reply.length + 1, reply.length + 1)];
        
        //回复的对象
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(bbs.realName.length + 2 + reply.length, bbs.toRealName.length + 1)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(bbs.realName.length + 2 + reply.length, bbs.toRealName.length + 1)];
        
        //回复的内容
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(bbs.realName.length + 3 + reply.length + bbs.toRealName.length, bbs.content.length)];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"101010"] range:NSMakeRange(bbs.realName.length + 3 + reply.length + bbs.toRealName.length, bbs.content.length)];
        cell.textLabel.attributedText = att;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:row];
    self.selectID = bbs.id;
    self.commentField.placeholder = @"Reply";
    [self.commentField becomeFirstResponder];
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:indexPath.row];
    return 10 + bbs.contentHeight;
}


@end
